package com.share.shareplatform.shareorder.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.share.shareplatform.pojo.SecurityUser;

import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Constants;
import com.share.shareplatform.util.Result;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Set;

/*
* 登录成功
*
* */
@Component
@Slf4j
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    public static final String RETURN_TYPE = "json"; // 登录成功时，用来判断是返回json数据还是跳转html页面

    @Autowired
    private ObjectMapper objectMapper;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    //成功后将token发送给浏览器
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, IOException {
        log.info("登录成功");
        log.info("username=>" + request.getParameter("username"));
        if(RETURN_TYPE.equals("html")) {
            redirectStrategy.sendRedirect(request, response, "/user/index");
        } else {
            Result result= Result.getInstance(200,"登录成功");
            SecurityUser principal = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            String username =principal.getUsername();
            Long id=principal.getId();
            Set<GrantedAuthority> authorities = (Set)principal.getAuthorities();
            String authorityStr = AuthorityUtil.authorityCollectionToString(authorities);
            String token =  Jwts.builder()
                    //主题 放入用户名
                    .setSubject(username)
                    //自定义属性 放入用户拥有请求权限
                    .claim(Constants.Jwt.AUTHORITIES, authorityStr)
                    .claim("id",id+"")
                    //失效时间
                    .setExpiration(new Date(System.currentTimeMillis() + 60* 60 * 1000))
                    //签名算法和密钥
                    .signWith(SignatureAlgorithm.HS512, Constants.Jwt.KEY)
                    .compact();
            System.out.println(token);
            result.put(Constants.Jwt.TOKEN_HEAD,token);

            response.setContentType("application/json;charset=UTF-8");

            response.getWriter().write(objectMapper.writeValueAsString(result));
        }

    }
}

